<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-header">
            <i class="el-icon-s-order card-icon"></i>
            <div class="card-title">
              <h3>订单总数</h3>
              <p>{{ statistics.orderCount || 0 }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-header">
            <i class="el-icon-money card-icon"></i>
            <div class="card-title">
              <h3>订单总金额</h3>
              <p>¥{{ statistics.totalAmount || '0.00' }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-header">
            <i class="el-icon-s-finance card-icon"></i>
            <div class="card-title">
              <h3>佣金总额</h3>
              <p>¥{{ statistics.totalCommission || '0.00' }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-header">
            <i class="el-icon-wallet card-icon"></i>
            <div class="card-title">
              <h3>待结算佣金</h3>
              <p>¥{{ statistics.unsettledCommission || '0.00' }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <!-- 我的订单列表 -->
      <el-col :span="12">
        <el-card shadow="hover" class="dashboard-table-card">
          <div slot="header" class="card-header">
            <h3>我的订单</h3>
            <el-button type="text" @click="goToOrder">查看更多</el-button>
          </div>
          <el-table v-loading="loading" :data="allOrders" style="width: 100%" size="mini">
            <el-table-column prop="orderNo" label="订单编号" width="180"></el-table-column>
            <el-table-column prop="totalAmount" label="金额" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.totalAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="viewOrder(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="allOrders.length === 0" class="empty-data">
            暂无订单数据
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="allOrders.length > 0">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="listQuery.page"
              :page-sizes="[5, 10, 20]"
              :page-size="listQuery.size"
              layout="total, sizes, prev, pager, next"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
      
      <!-- 配送信息 -->
      <el-col :span="12">
        <el-card shadow="hover" class="dashboard-table-card">
          <div slot="header" class="card-header">
            <h3>配送信息</h3>
            <el-button type="text" @click="goToDelivery">查看更多</el-button>
          </div>
          <div v-loading="deliveryLoading">
            <div v-if="hasRoute" class="delivery-info">
              <p><strong>路线名称：</strong>{{ routeInfo.route.name }}</p>
              <p><strong>状态：</strong>
                <el-tag :type="routeInfo.route.status === 1 ? 'success' : 'info'">
                  {{ routeInfo.route.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </p>
              <p><strong>描述：</strong>{{ routeInfo.route.description }}</p>
            </div>
            <div v-else class="empty-data">
              您当前未被分配到任何配送路线
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getLeaderDashboardData } from '@/api/leader'
import { getRouteByLeaderId } from '@/api/delivery-route'
import { getLeaderOrders } from '@/api/order'

export default {
  name: 'LeaderDashboard',
  data() {
    return {
      loading: false,
      deliveryLoading: false,
      leaderId: null,
      statistics: {
        orderCount: 0,
        totalAmount: '0.00',
        totalCommission: '0.00',
        unsettledCommission: '0.00'
      },
      allOrders: [],
      total: 0,
      listQuery: {
        page: 1,
        size: 5
      },
      hasRoute: false,
      routeInfo: {
        route: {},
        items: []
      }
    }
  },
  created() {
    this.leaderId = Number(localStorage.getItem('leaderId'))
    this.fetchDashboardData()
    this.fetchDeliveryInfo()
  },
  methods: {
    fetchDashboardData() {
      this.loading = true
      getLeaderDashboardData(this.leaderId).then(response => {
        if (response) {
          // 处理统计数据
          this.statistics = response.statistics || {
            orderCount: 0,
            totalAmount: '0.00',
            totalCommission: '0.00',
            unsettledCommission: '0.00'
          }
          
          // 处理所有订单
          this.allOrders = response.allOrders || []
          this.total = this.statistics.orderCount || 0
        }
        this.loading = false
      }).catch((error) => {
        console.error('获取仪表盘数据失败:', error)
        this.statistics = {
          orderCount: 0,
          totalAmount: '0.00',
          totalCommission: '0.00',
          unsettledCommission: '0.00'
        }
        this.allOrders = []
        this.total = 0
        this.loading = false
      })
    },
    fetchDeliveryInfo() {
      this.deliveryLoading = true
      getRouteByLeaderId(this.leaderId).then(response => {
        if (response && response.route) {
          this.hasRoute = true
          this.routeInfo = {
            route: response.route || {},
            items: response.items || []
          }
        } else {
          this.hasRoute = false
          this.routeInfo = {
            route: {},
            items: []
          }
        }
        this.deliveryLoading = false
      }).catch(() => {
        this.hasRoute = false
        this.routeInfo = {
          route: {},
          items: []
        }
        this.deliveryLoading = false
      })
    },
    fetchAllOrders() {
      // 如果是第一页且已经有数据，则不需要再次请求
      if (this.listQuery.page === 1 && this.allOrders.length > 0) {
        return
      }
      
      this.loading = true
      
      // 构建请求参数
      const params = {
        page: this.listQuery.page - 1, // 后端从0开始计数
        size: this.listQuery.size
      }
      
      getLeaderOrders(this.leaderId, params).then(response => {
        if (response && response.records) {
          this.allOrders = response.records
          this.total = response.total
        } else if (Array.isArray(response)) {
          this.allOrders = response
          this.total = response.length
        } else {
          this.allOrders = []
          this.total = 0
        }
        this.loading = false
      }).catch(() => {
        this.allOrders = []
        this.total = 0
        this.loading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchAllOrders()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchAllOrders()
    },
    viewOrder(order) {
      this.$router.push(`/leader/order`)
    },
    goToOrder() {
      this.$router.push('/leader/order')
    },
    goToDelivery() {
      this.$router.push('/leader/delivery')
    },
    getOrderStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '已处理',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知'
    },
    getOrderStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'primary',
        2: 'warning',
        3: 'success',
        4: 'danger'
      }
      return typeMap[status] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  
  .dashboard-card {
    height: 120px;
    
    .card-header {
      display: flex;
      align-items: center;
      
      .card-icon {
        font-size: 48px;
        color: #409EFF;
        margin-right: 20px;
      }
      
      .card-title {
        h3 {
          font-size: 16px;
          color: #666;
          margin: 0 0 10px 0;
        }
        
        p {
          font-size: 24px;
          color: #333;
          margin: 0;
        }
      }
    }
  }
  
  .mt-20 {
    margin-top: 20px;
  }
  
  .dashboard-table-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      h3 {
        font-size: 16px;
        margin: 0;
      }
    }
    
    .empty-data {
      padding: 30px 0;
      text-align: center;
      color: #909399;
    }
    
    .delivery-info {
      padding: 10px;
      
      p {
        margin: 10px 0;
      }
    }
  }
  
  .pagination-container {
    margin-top: 15px;
    text-align: right;
  }
}
</style> 